<template>
  <div class="content-manage">
    <el-scrollbar style="width: 100%">
      <div class="content-manage-container">
        <ContentCrumb />
        <div class="content-list">
          <h2 class="setting-header">
            <strong>我的发布</strong>
          </h2>
          <el-tabs v-model="curState" @tab-change="handleTabChange">
            <el-tab-pane v-for="item in tabArr" :key="item.state" :label="item.name" :name="item.state" />
          </el-tabs>
          <SearchCmp ref="searchCmpRef" v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" style="margin-bottom: 10px" />
          <!-- 表格样式 -->
          <div class="ruifox-list">
            <RuifoxTable
              :key="curState"
              :loading="tableLoading"
              v-model:tableData="tableData"
              v-model:fieldList="fieldList"
              :default-index="true"
              :tableProps="tableProps"
              @handleSearch="handleSearch"
            >
              <!-- 置顶 -->
              <template #is_top="{ element }">
                <div class="table-td-top">
                  <span :class="{ 'ding-yes': element.is_top, 'ding-no': !element.is_top }" @click="handleTop(element)">顶</span>
                </div>
              </template>
              <!-- 锁定 -->
              <template #is_lock="{ element }">
                <el-tag type="danger" v-if="element.is_lock">已锁定</el-tag>
                <el-tag type="success" v-else>未锁定</el-tag>
              </template>
              <!-- 创建时间 -->
              <template #create_time="{ element }">
                {{ dayjs(element.create_time).format('YYYY-MM-DD HH:mm:ss') }}
              </template>
              <!-- 操作 -->
              <template #options="{ element }">
                <div class="table-td-option">
                  <el-button
                    v-if="hasPermission(['content:manage:setting:edit']) && [99, 1, 3].includes(curState)"
                    type="primary"
                    link
                    @click="handleEdit(element)"
                    :disabled="!element.is_lock ? false : true"
                  >
                    编辑
                  </el-button>
                  <el-button type="primary" link v-if="hasPermission(['content:manage:setting:preview'])" @click="handleViewFront(element)">前台浏览</el-button>
                  <el-dropdown>
                    <span class="el-dropdown-link unmover">
                      <i class="iconfont">&#xe78d;</i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="hasPermission(['content:manage:revoke']) && [99].includes(curState)" @click="handleRevoke(element)" :disabled="!element.is_lock ? false : true">撤稿</el-dropdown-item>
                        <el-dropdown-item v-if="hasPermission(['content:manage:push']) && [99].includes(curState)" @click="handlePush(element)">投递</el-dropdown-item>
                        <el-dropdown-item v-if="hasPermission(['content:manage:lock']) && [99, 0, 1, 2, 3, 4].includes(curState)" @click="handleLock(element)">
                          {{ element.is_lock ? '解锁' : '上锁' }}
                        </el-dropdown-item>
                        <el-dropdown-item v-if="hasPermission(['content:manage:top']) && [99, 0, 1, 2, 3, 4].includes(curState)" @click="handleTop(element)">
                          {{ element.is_top ? '取消置顶' : '置顶' }}
                        </el-dropdown-item>
                        <el-dropdown-item v-if="hasPermission(['content:manage:archive']) && [99, 0, 1, 2, 3].includes(curState)" @click="handleArchive(element)">手动归档</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </RuifoxTable>
          </div>
          <PaginationView
            :total="queryData.total"
            :pageSize="queryData.pageSize"
            :currentPage="queryData.currentPage"
            :allChoose="isAllChooseBtn"
            :pageChoose="isPageChooseBtn"
            :checkedNum="checkedNum"
            :canChoose="false"
            @changeSize="handleSizeChange"
            @currentChange="handleCurrentChange"
            @changePageChoose="handlePageChoose"
            @changeAllChoose="handleAllChoose"
            @cancelChoose="handleResetPagination"
            @invertChoose="handleInvertChoose"
            @refreshList="getTableData"
          />
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updateSystemData, getMyPublish } from '@/api/content'
import { getModelByCatId } from '@/api/model'
import { tableList as mixTable, hasPermission } from '@ruifox-cms/utils'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'

const router = useRouter()
// 分页逻辑局部混入
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleResetPagination
} = mixTable({
  getListApi: getMyPublish
})

// 顶部tab及各状态可操作选项（注意添加state不要重复）
const curState = ref(99)
if (router.currentRoute.value.query.state) {
  curState.value = Number(router.currentRoute.value.query.state)
}
const tabArr = reactive([
  {
    state: 99,
    name: '已发布'
  },
  {
    state: 0,
    name: '审核中'
  },
  {
    state: 1,
    name: '草稿箱'
  },
  {
    state: 2,
    name: '撤稿箱'
  },
  {
    state: 3,
    name: '已退稿'
  },
  {
    state: 4,
    name: '已归档'
  }
])
const searchCmpRef = ref(null)
const handleTabChange = () => {
  searchCmpRef.value.clearForm(queryData)
  searchCmpRef.value.showTags()
  queryData.state = curState.value
  handleResetPagination()
  getTableData()
}

// 表头数据处理
const fieldList = ref([
  {
    name: '置顶',
    field: 'is_top',
    width: 30,
    hideTitle: true,
    fixed: 'left'
  },
  {
    name: '标题',
    field: 'title',
    width: 450,
    fixed: 'left',
    showTextTip: true
  },
  {
    name: '来源栏目',
    field: 'category'
  },
  {
    name: '锁定状态',
    field: 'is_lock'
  },
  {
    name: '创建时间',
    field: 'create_time'
  },
  {
    name: '操作',
    field: 'options',
    width: 150,
    fixed: 'right'
  }
])
const tableProps = reactive({
  labelKey: 'name',
  valueKey: 'field'
})
const searchCmpArray = ref([{ label: '标题', key: 'title' }])
// 内容列表查询参数
const defaultQueryData = reactive({
  currentPage: 1,
  pageSize: 10,
  state: router.currentRoute.value.query.state || 99
})
Object.assign(queryData, defaultQueryData)
/*************************************************************行操作*************************************/
// 编辑内容
const handleEdit = async data => {
  const res = await getModelByCatId({ catId: data.cat_id })
  if (res.code !== 20000) {
    ElMessage.error('获取模型失败，无法预览')
    return
  }
  const toUrl = router.resolve({
    path: '/content/manage/setting',
    query: {
      modelId: res.data.id,
      publishType: res.data.publishType,
      catId: data.cat_id,
      dataId: data.state === 1 ? null : data.data_id,
      draftId: data.state === 1 ? data.data_id : null,
      isReject: data.state === 3 ? true : null
    }
  })
  window.open(toUrl.href, '_blank')
}

// 撤稿
const handleRevoke = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否删除该内容？</p><span style="font-size: 14px;color: #FF5240;">清除后内容将无法恢复</span></div>', '删除确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const obj = {
      catId: data.cat_id,
      id: data.id,
      state: 2
    }
    updateSystemData(obj).then(res => {
      if (res.code === 20000) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      getTableData()
    })
  })
}

// 上锁解锁
const handleLock = data => {
  const obj = {
    catId: data.cat_id,
    id: data.id,
    isLock: data.is_lock ? 0 : 1
  }
  updateSystemData(obj).then(res => {
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: data.isLock ? '解锁成功' : '上锁成功',
        type: 'success'
      })
    }
    getTableData()
  })
}

// 置顶取消置顶
const handleTop = data => {
  const obj = {
    catId: data.cat_id,
    id: data.id,
    isTop: data.is_top ? 0 : 1
  }
  updateSystemData(obj).then(res => {
    if (res.code === 20000) {
      ElMessage({
        showClose: true,
        message: data.isTop ? '取消置顶成功' : '置顶成功',
        type: 'success'
      })
    }
    getTableData()
  })
}

// 前台浏览
const handleViewFront = data => {
  if (data.url) {
    // 已发布就直接访问前台地址
    window.open(data.url, '_blank')
  } else {
    // 无url提示无法预览
    ElMessage.warning('无法预览')
  }
}

// 手动归档
const handleArchive = data => {
  ElMessageBox.confirm('<div><p style="font-size: 16px;margin-bottom: 15px;">是否归档所选稿件</p></div>', '归档确认', {
    dangerouslyUseHTMLString: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(async () => {
    const obj = {
      catId: data.cat_id,
      id: data.id,
      state: 4
    }
    updateSystemData(obj).then(res => {
      if (res.code === 20000) {
        ElMessage({
          showClose: true,
          message: '删除成功',
          type: 'success'
        })
      }
      getTableData()
    })
  })
}

onMounted(() => {
  getTableData()
})
</script>

<style lang="scss" scoped>
.content-manage {
  flex: 1;
  height: calc(100vh - 65px);
  .content-manage-container {
    flex: 1;
    padding: 10px;
  }
  .content-list {
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 0 5px rgba(#000, 0.1);
    width: 100%;
    margin-top: 15px;
    box-sizing: border-box;
    min-width: 650px;
    padding: 20px;
    .ruifox-card-options {
      .ruifox-card-btn {
        i {
          margin-right: 5px;
        }
      }
    }
    .ruifox-list {
      .collect-btn i {
        color: #ccc;
        cursor: pointer;
      }
      .collect-btn.is-collect i {
        color: $mainColor;
      }
      .table-td-top {
        width: 18px;
        min-width: 18px;
        .ding-yes {
          display: inline-block;
          width: 16px;
          height: 16px;
          font-size: 12px;
          color: $white;
          line-height: 16px;
          text-align: center;
          background-color: #ff5240;
          cursor: pointer;
          margin-right: 5px;
        }
        .ding-yes:hover {
          background-color: #f78a7e;
        }
        .ding-no {
          display: inline-block;
          cursor: pointer;
          width: 16px;
          height: 16px;
          font-size: 12px;
          color: $white;
          line-height: 16px;
          text-align: center;
          background-color: #d7d7d7;
          margin-right: 5px;
          visibility: hidden;
        }
        .ding-no:hover {
          background-color: #817f7f;
        }
      }
      .table-td-title {
        display: flex;
        align-items: center;
        .title-tips {
          .iconfont {
            font-size: 14px;
            color: $mainColor;
            margin-right: 3px;
          }
          span {
            color: #aaa;
            margin-right: 20px;
            position: relative;
          }
          span + span:before {
            content: '|';
            position: absolute;
            left: -10px;
            top: -8px;
          }
        }
        .title-box {
          display: flex;
          justify-content: center;
          align-items: center;
          p {
            @include textEllipsis(16px, 1);
          }
          .iconimg {
            display: inline-block;
            width: 16px;
            margin-right: 5px;
            i {
              color: #2cbf77;
              font-size: 15px;
            }
          }
          .a-icon {
            display: inline-block;
            width: 16px;
            background-color: $mainColor;
            color: $white;
            line-height: 16px;
            text-align: center;
            i {
              font-size: 14px;
            }
          }
          .p-icon {
            display: flex;
            align-items: center;
            width: 20px;
            color: #2cbf77;
            i {
              font-size: 18px;
            }
          }
          .thumb-box {
            display: flex;
            align-items: center;
          }
        }
      }
    }
  }
  .button-box {
    padding-right: 10px;
    .el-button + .el-button {
      margin-left: 0;
    }
    flex-grow: 0;
    position: relative;
    i {
      position: absolute;
      right: -13px;
      top: 5px;
      color: $mainColor;
      cursor: pointer;
    }
  }
  .libarary-table {
    width: 100%;
    ::v-deep(.el-table__cell) {
      height: 50px;
      padding: 4px 0;
    }
    .option-btn {
      width: 35px;
    }
  }
}
</style>
